express = require 'express'
router = express.Router()

crypto = require 'crypto'
child_process = require 'child_process'

schema = require '../modules/schema.js'
Teacher = schema.Teacher
Student = schema.Student
Key = schema.Key
SC = schema.SC
Course = schema.Course

Handler = require '../modules/err_handler.js'

errHandler = Handler.errHandler
dataHandler = Handler.dataHandler

Check = require '../modules/login_check.js'
checkLogin = Check.checkLogin
notLogin = Check.notLogin

xlsx = require "node-xlsx"


# login module


router.get "/*",(req,res,next)->
	console.log req.cookies
	next()

router.post '/teacher/login',(req,res)->
	if not req.body.tid or not req.body.passwd
		req.session.err = '请正确输入教师id和密码'
		errHandler req,res
	else
		Teacher.findOne '_id':req.body.tid,(err,teacher)->
			if err
				req.session.err = err
				errHandler req,res
			else if not teacher?
				req.session.err = '请正确输入id和密码'
				errHandler req,res
			else
				md5 = crypto.createHash 'md5'
				md5.update req.body.passwd
				passwd = md5.digest 'hex'
				if passwd is teacher.passwd
					req.session.user = teacher
					req.session.type = 't'
					dataHandler res,'redirect','/teacher'
				else
					req.session.err = '请正确输入教师id和密码'
					errHandler req,res

# check login

router.all '/teacher/*',checkLogin
router.get '/teacher',checkLogin

# main page

router.get '/teacher',(req,res)->
	res.render 'teacher/index','title':'教师管理界面','teacher':req.session.user

# interface

router.get '/teacher/interface/info',(req,res)->
	if req.session.type is 't'
		dataHandler res,'ok',tid:req.session.user._id,tname:req.session.user.tname

router.get '/teacher/interface/courseInfo/:cid',(req,res)->
	Course.findOne '_id':req.param 'cid'
		.exec (err,course)->
			if err?
				req.session.err = err
				errHandler req,res
			else if not course?
				req.session.err = 'no this course'
				errHandler req,res
			else
				dataHandler res,'ok',course

# course 

router.get '/teacher/course/:cid',(req,res)->
	Course.findOne '_id':req.param 'cid'
		.exec (err,course)->
			if err?
				req.session.err = err
				errHandler req,res
			else if not course?
				req.session.err = 'no this course'
				errHandler req,res
			else
				res.render 'teacher/course','teacher':req.session.user,'course':course._id,'times':course.signup_times,'cname':course.cname

router.get '/teacher/course/:cid/list.xlsx',(req,res)->
	Course.findOne _id:req.param "cid"
		.exec (err,course)->
			if err?
				req.session.err = err
				errHandler req,res
			else if not course?
				req.session.err = "no this course"
				errHandler req,res
			else if course.signup_times is 0
				req.session.err = "no signup"
				errHandler req,res
			else
				x_head = ["序号","学号","姓名"]
				for _t in [1..course.signup_times]
					x_head.push "考勤#{_t},"
				for _t in [1..4]
					x_head.push "作业#{_t},"
				x_head.push "平时成绩"
				x_head.push "期末成绩"
				x_head.push "学期总评"
				x_head.push "备注"
				getSignup = (sc,_i)->
					signup = []
					signup.push _i
					signup.push sc.student._id
					signup.push sc.student.sname
					for time in [1..course.signup_times]
						signup.push ((time,sp)->
							for _t in sp
								if _t.time is time
									if _t._id is "000000000000"
										return "i"
									else
										return "p"
							return "a"
						)(time,sc.signup)
					for _t in [1..8]
						signup.push ""
					signup
				if req.cookies.dstudents?
					dstudents = req.cookies.dstudents.split(",")
				else
					dstudents = []
				SC.find {"course":course._id,"student":{"$not":{"$in":dstudents}}}
					.populate "student"
					.exec (err,scs)->
						if err?
							req.session.err = err
							errHandler req,res
						else if not scs?
							req.session.err = "你确定没有ban掉所有学生？或者无人选课"
							errHandler req,res
						else
							file = []
							classed = []
							for sc in scs
								if typeof classed[sc.student.sclass] is "undefined"
									classed[sc.student.sclass] = []
								classed[sc.student.sclass].push sc
							for _class of classed
								sheet = []
								sheet.push x_head
								_i = 1
								classed[_class].sort (a,b)->
									a.student._id/1 - b.student._id/1
								for st in classed[_class]
									sheet.push getSignup st,_i
									_i += 1
								file.push {'name':_class,'data':sheet}
							buffer = xlsx.build file
							res.writeHead 200,{
								'Content-Type':'text/xlsx',
								'Content-Disposition':'hh.xlsx'
							}
							res.write buffer
							res.end()

router.get '/teacher/course/:cid/del',(req,res)->
	Teacher.findOne {'_id':req.session.user._id}
		.exec (err,teacher)->
			if err?
				req.session.err = err
				errHandler req,res
			else if not teacher?
				req.session.err = "no this teacher"
				errHandler req,res
			else
				indexId = (c,id)->
					for _t of c
						if c[_t]._id is id
							return _t
					return -1
				index = indexId teacher.course,req.param 'cid'
				if index isnt -1
					teacher.course[index].del = true
					teacher.save (err)->
						if err?
							req.session.err = err
							errHandler req,res
						else
							res.redirect '/teacher'
				else
					req.session.err = "no this course"
					errHandler req,res



							
router.get '/teacher/course/student/:cid',(req,res)->
	SC.find 'course':req.param 'cid'
		.populate 'student','sname sclass'
		.populate 'course','signup_times time_each'
		.exec (err,scs)->
			if err?
				req.session.err = err
				errHandler req,res
			else
				dataHandler res,'ok',scs

router.post '/teacher/addCourse',(req,res)->
	if not req.body.cname
		req.session.err = '请输入课程名称'
		errHandler req,res
	else
		random = Math.ceil (Math.random() * 1000)
		course = new Course 'cname':req.body.cname,'random':random
		course.save (err,cou)->
			if err
				req.session.err = err
				errHandler req,res
			else
				Teacher.update '_id':req.session.user._id,
					'$addToSet':'course':'_id':cou._id,'cname':req.body.cname
					(err,teacher)->
						if err?
							console.log err
					,true
				info = 'cid':cou._id,'cname':cou.cname
				dataHandler res,'ok',info

router.get '/teacher/getCourse',(req,res)->
	Teacher.findOne '_id':req.session.user._id,'course',(err,teacher)->
		if err?
			req.session.err = err
			errHandler req,res
		else if not teacher
			req.session.user = null
			req.session.type = null
			res.redirect '/'
		else
			dataHandler res,'ok',teacher.course

router.get '/teacher/zoom_qr/:cid',(req,res)->
	res.render 'teacher/zoom_qr',cid:req.param "cid"



# signup module
#
# node should just run go module,make 'time' ++,adn return
# the path of xlxs file we gen
#

router.post '/teacher/course/:cid/signup',(req,res)->
	Course.findOne '_id':req.param 'cid'
		.exec (err,course)->
			if not course?
				req.session.err = '查无此课'
				errHandler req,res
			else
				if not req.body.number/1
					req.session.err = '输入错误'
					return errHandler req,res
				else if req.body.number/1 > 500
					req.session.err = '生成数过大'
					return errHandler req.res
				gen = child_process.spawn 'bin/genSeed',['-t'
					,req.body.number
					,req.param('cid')
					,course.random
					,course.signup_times]
				console.log '-t'
					,req.body.number
					,req.param('cid')
					,course.random
					,course.signup_times
				gen.on 'exit',(code)->
					if code is 0
						dataHandler res,'get',{}
					else
						req.session.err = 'unknow error'
						errHandler req,res

#sign code binding!
router.post '/teacher/course/:cid/binding',(req,res)->
	if not req.body.code?
		req.session.err = '请输入封皮激活码'
		errHandler req,res
	else
		Course.findOne '_id':req.param 'cid'
			.exec (err,c)->
				if err
					req.session.err = err
					errHandler req,res
				else if not c?
					req.session.err = '请输入正确的课程号'
					errHandler req,res
				else
					Key.find 'tmp':req.body.code
					.exec (err,keys)->
						if err?
							req.session.err = err
							errHandler req,res
						else if not keys? || not keys[0]
							req.session.err = '请输入正确的激活码'
							errHandler req,res
						else if keys[0].cid && keys[0].cid isnt ""
							console.log keys[0]
							req.session.err = '激活码输入错误或激活码已被其他老师使用'
							errHandler req,res
						else
							Key.update 'tmp':req.body.code,
									'$set':'cid':c._id,'time':c.signup_times+1,
										'multi':true
							.exec (err,key)->
								if err?
									req.session.err = err
									errHandler req,res
								else if !key?
									req.session.err = '激活码输入错误或激活码已被其他老师使用'
									errHandler req,res
								else
									SC.find {'course':c._id,"$and":[{"nextIll":{"$ne":null}},{"nextIll":{"$ne":""}}]}
										.exec (err,scs)->
											if err?
												console.log err
											else if not scs
												console.log 'no'
											else
												now = new Date()
												md = "#{now.getMonth()}-#{now.getDate()}"
												for _sc in scs
													if _sc.nextIll is md
														_sc.nextIll = ""
														_sc.signup.push({"time":c.signup_times+1,"_id":"000000000000"})
												Course.update '_id':req.param('cid'),
														'$inc':{signup_times:1},
														'$addToSet':time_each:times:c.signup_times+1,time:Date()
												.exec (err,cou)->
													if err?
														req.session.err = err
														errHandler req,res
													else if not cou?
														console.log "!!!!"
													else
														cp = child_process.spawn 'bin/courseHelper',[]
														cp.on 'exit',()->
															dataHandler res,'ok',{}

#get keys
router.get '/key/:keyname',(req,res)->
	if req.session.type? && req.session.type = 't'
		res.download "keys/#{req.param 'keyname' }"
	else
		res.writeHead 403,'Content-Type':'text/html'
		res.end "403"

module.exports = router
						




	

